// pages/interested/interested.js
import { queryApplicationProjectService } from "../../api/project";

Page({
  data: {
    projectList: [],
    pageInfo: {
      pageNum: 1,
      pageSize: 10,
      hasMore: true,
      loading: false,
    },
  },

  onLoad(options) {
    if (this.checkLoginStatus()) {
      this.loadProjectData(true);
    }
  },

  /**
   * 获取认证头
   */
  getAuthHeader() {
    const token = wx.getStorageSync("token");
    return token ? {
      "content-type": "application/json",
      Authorization: token,
    } : {
      "content-type": "application/json",
    };
  },

  /**
   * 检查登录状态
   */
  checkLoginStatus() {
    const token = wx.getStorageSync("token");
    if (!token) {
      wx.showModal({
        title: "提示",
        content: "请先登录",
        showCancel: true,
        cancelText: "取消",
        confirmText: "去登录",
        success: (res) => {
          if (res.confirm) {
            wx.redirectTo({ url: "/pages/login/login" });
          }
        },
      });
      return false;
    }
    return true;
  },

  /**
   * 从缓存获取学校名称
   */
  getSchoolNameFromCache(schoolId) {
    try {
      const schoolList = wx.getStorageSync("schoolList") || [];
      const school = schoolList.find(item => item.id == schoolId);
      return school ? school.schoolName : schoolId;
    } catch (error) {
      console.warn("获取学校名称失败:", error);
      return schoolId;
    }
  },

  /**
   * 加载项目数据
   */
  loadProjectData(refresh = false) {
    const pageInfo = this.data.pageInfo;

    if (!this.checkLoginStatus() || pageInfo.loading || (!refresh && !pageInfo.hasMore)) {
      return;
    }

    if (refresh) {
      pageInfo.pageNum = 1;
      pageInfo.hasMore = true;
    }

    this.setData({ "pageInfo.loading": true });
    wx.showLoading({ title: "加载中..." });

    const requestData = {
      pageNum: pageInfo.pageNum.toString(),
      pageSize: pageInfo.pageSize.toString(),
    };

    // 使用统一的 API 调用方式
    queryApplicationProjectService(requestData)
      .then((res) => {
        wx.hideLoading();

        if (res.code === 500) {
          this.handleApiError(res);
          return;
        }

        if (res.code === 200) {
          const responseData = res.data || [];
          
          let newProjects = [];
          if (Array.isArray(responseData)) {
            newProjects = responseData.map((item, index) => {
              const project = item.project || {};
              return {
                id: item.id || index,
                projectId: project.id,
                projectName: project.projectName || "未知项目",
                projectInfo: project.projectInfo || "",
                school: this.getSchoolNameFromCache(project.school), // 从缓存获取学校名称
                direction: project.direction || "",
                memberCount: project.memberCount || 0,
                crossSchool: project.crossSchool === 1,
                educationRequirement: this.getEducationRequirementText(project.educationRequirement),
                skillSummary: project.skillSummary || "",
                skillDetails: project.skillDetails || "",
                createdAt: project.createdAt || "",
                updatedAt: project.updatedAt || "",
                creatorOpenid: project.creatorOpenid || "",
                isApproved: item.isApproved,
                approveReason: item.approveReason || "",
                approveTime: item.approveTime || "",
                phone: item.phone || "",
                schoolname: project.schoolname || "",
                email: item.email || "",
                nickname: item.nickname || "",
                statusText: this.getStatusText(item.isApproved),
                statusColor: this.getStatusColor(item.isApproved),
                canWithdraw: item.isApproved === 0,
              };
            });

            // 按投递时间倒序排列
            newProjects.sort((a, b) => new Date(b.createdAt || "") - new Date(a.createdAt || ""));
          }

          // 修复无限循环bug：严格判断是否有更多数据
          const hasMore = newProjects.length === pageInfo.pageSize && newProjects.length > 0;
          
          let updatedList;
          if (refresh) {
            updatedList = newProjects;
          } else {
            updatedList = [...this.data.projectList, ...newProjects];
          }

          this.setData({
            projectList: updatedList,
            "pageInfo.pageNum": pageInfo.pageNum + 1,
            "pageInfo.hasMore": hasMore, // 修复：严格判断是否还有更多数据
            "pageInfo.loading": false,
          });

          if (refresh) {
            wx.stopPullDownRefresh();
          }
        } else if (res.code === 208) {
          this.handleAuthError();
        } else {
          this.handleLoadError(`获取数据失败: ${res.message || res.code}`);
        }
      })
      .catch((err) => {
        wx.hideLoading();
        this.handleLoadError("网络连接异常，请重试");
      });
  },

  /**
   * 错误处理方法
   */
  handleApiError(errorData) {
    this.setData({ "pageInfo.loading": false });
    const errorMessage = errorData?.message || "服务器错误";
    
    wx.showModal({
      title: errorMessage.includes("No static resource") ? "API配置错误" : "服务器错误",
      content: errorMessage,
      showCancel: false,
      confirmText: "我知道了",
    });
    wx.stopPullDownRefresh();
  },

  handleAuthError() {
    this.setData({ "pageInfo.loading": false });
    wx.removeStorageSync("token");
    
    wx.showModal({
      title: "认证失败",
      content: "登录已过期，请重新登录",
      showCancel: false,
      confirmText: "确定",
      success: () => wx.redirectTo({ url: "/pages/login/login" }),
    });
    wx.stopPullDownRefresh();
  },

  handleLoadError(message) {
    this.setData({ "pageInfo.loading": false });
    wx.showToast({ title: message, icon: "error", duration: 2000 });
    wx.stopPullDownRefresh();
  },

  /**
   * 工具方法
   */
  getStatusText(isApproved) {
    const statusMap = { 0: "待审核", 1: "已通过", 2: "已拒绝" };
    return statusMap[isApproved] || "未知状态";
  },

  getStatusColor(isApproved) {
    const colorMap = { 0: "#1890ff", 1: "#52c41a", 2: "#ff4d4f" };
    return colorMap[isApproved] || "#666666";
  },

  getEducationRequirementText(educationRequirement) {
    const eduMap = { 1: "大专", 2: "本科", 3: "研究生", 4: "博士" };
    return eduMap[Number(educationRequirement)] || "不限";
  },

  /**
   * 事件处理方法
   */
  viewApprovalDetail(e) {
    const item = e.currentTarget.dataset.item;
    if (!item) {
      wx.showToast({ title: "数据错误", icon: "error" });
      return;
    }

    const { projectName, isApproved, approveReason, approveTime } = item;
    const statusText = this.getStatusText(isApproved);
    
    let content = `项目名称：${projectName}\n审核状态：${statusText}`;
    if (approveTime) content += `\n审核时间：${approveTime}`;
    if (approveReason) {
      const reasonLabel = isApproved === 1 ? "通过原因" : isApproved === 2 ? "拒绝原因" : "备注";
      content += `\n${reasonLabel}：${approveReason}`;
    }

    wx.showModal({
      title: "审核详情",
      content: content,
      showCancel: false,
      confirmText: "我知道了",
    });
  },

  withdrawApplication(e) {
    const item = this.data.projectList[e.currentTarget.dataset.index];
    
    if (!this.checkLoginStatus()) return;

    if (item.isApproved !== 0) {
      const messageMap = { 1: "申请已通过，无法撤销", 2: "申请已被拒绝，无法撤销" };
      wx.showToast({
        title: messageMap[item.isApproved] || "当前状态无法撤销",
        icon: "none",
        duration: 2000,
      });
      return;
    }

    wx.showModal({
      title: "确认撤销",
      content: "确定要撤销这个项目申请吗？撤销后将无法恢复。",
      confirmColor: "#ff4d4f",
      success: (res) => {
        if (res.confirm) {
          wx.showModal({
            title: "撤销失败",
            content: "申请已超过撤回时间",
            showCancel: false,
            confirmText: "我知道了",
          });
        }
      },
    });
  },

  contactCreator(e) {
    const item = e.currentTarget.dataset.item;
    
    if (item.isApproved !== 1) {
      wx.showToast({ title: "申请未通过，暂无法联系", icon: "none" });
      return;
    }

    const { projectId, projectName, phone = "", email = "", nickname = "" } = item;
    wx.navigateTo({
      url: `/pages/teamInfo/teamInfo?projectId=${projectId}&projectName=${encodeURIComponent(projectName)}&phone=${phone}&email=${email}&nickname=${encodeURIComponent(nickname)}`,
    });
  },

  viewProjectDetail(e) {
    const item = e.currentTarget.dataset.item;
    const content = `项目名称：${item.projectName}
项目介绍：${item.projectInfo}
学校：${item.school}
方向：${item.direction}
队伍规模：${item.memberCount}
跨校合作：${item.crossSchool ? "是" : "否"}
学校要求：${item.educationRequirement}
技能要求：${item.skillSummary}`;

    wx.showModal({
      title: "项目详情",
      content: content,
      showCancel: false,
      confirmText: "我知道了",
    });
  },

  /**
   * 生命周期方法
   */
  onShow() {
    const token = wx.getStorageSync("token");
    if (token && this.data.projectList.length === 0) {
      this.loadProjectData(true);
    }
  },

  onPullDownRefresh() {
    this.loadProjectData(true);
  },

  onReachBottom() {
    this.loadProjectData(false);
  },

  onReady() {},
  onHide() {},
  onUnload() {},
  onShareAppMessage() {},
});